/**
 * 登录
 * All rights Reserved, Designed By 信鸥科技
 * project : committee
 * Created by youquer on 17/10/29.
 * 注意：本内容仅限于信鸥科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 * Description:
 *
 */

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import { Form, Input, Tabs, Button, Icon, Checkbox, Row, Col, Alert } from 'antd';

import TweenOne, { TweenOneGroup } from 'rc-tween-one';
import ticker from 'rc-tween-one/lib/ticker';
import InputNumber from 'antd/lib/input-number';
import Radio from 'antd/lib/radio';
import enquire from 'enquire.js';
import styles from './Login.less';
const FormItem = Form.Item;
const { TabPane } = Tabs;
import PropTypes from 'prop-types';
import imgLogo from '@/assets/logoS.png';
import logoImgs from '@/assets/logoS.png';
import logoImg from '@/assets/logoS.png';
import global from '@/utils/global';

const RadioGroup = Radio.Group;

class LogoGather extends React.Component {
  static propTypes = {
    image: PropTypes.string,
    w: PropTypes.number,
    h: PropTypes.number,
    pixSize: PropTypes.number,
    pointSizeMin: PropTypes.number,
  };

  static defaultProps = {
    image: imgLogo,
    w: 400,
    h: 400,
    pixSize: 30,
    pointSizeMin: 10,
  };

  constructor(props) {
    super(props);
    this.state = {
      account: '',
      pwd: '',
    };
    this.interval = null;
    this.gather = true;
    this.intervalTime = 9000;
  }

  componentDidMount() {
    this.dom = ReactDOM.findDOMNode(this);
    this.createPointData();
  }

  componentWillUnmount() {
    ticker.clear(this.interval);
    this.interval = null;
  }

  onMouseEnter = () => {
    if (!this.gather) {
      this.updateTweenData();
    }
    this.componentWillUnmount();
  };

  onMouseLeave = () => {
    if (this.gather) {
      this.updateTweenData();
    }
    this.interval = ticker.interval(this.updateTweenData, this.intervalTime);
  };

  setDataToDom(data, w, h) {
    this.pointArray = [];
    const number = this.props.pixSize;
    for (let i = 0; i < w; i += number) {
      for (let j = 0; j < h; j += number) {
        if (data[((i + j * w) * 4) + 3] > 150) {
          this.pointArray.push({ x: i, y: j });
        }
      }
    }
    const children = [];
    this.pointArray.forEach((item, i) => {
      const r = Math.random() * this.props.pointSizeMin + this.props.pointSizeMin;
      const b = Math.random() * 0.4 + 0.1;
      children.push((
        <TweenOne className={styles.point_wrapper} key={i} style={{ left: item.x, top: item.y }}>
          <TweenOne
            className={styles.point}
            style={{
              width: r,
              height: r,
              opacity: b,
              backgroundColor: `rgb(${Math.round(Math.random() * 95 + 160)},255,255)`,
            }}
            animation={{
              y: (Math.random() * 2 - 1) * 10 || 5,
              x: (Math.random() * 2 - 1) * 5 || 2.5,
              delay: Math.random() * 1000,
              repeat: -1,
              duration: 3000,
              yoyo: true,
              ease: 'easeInOutQuad',
            }}
          />
        </TweenOne>
      ));
    });
    this.setState({
      children,
      boxAnim: { opacity: 0, type: 'from', duration: 800 },
    }, () => {
      this.interval = ticker.interval(this.updateTweenData, this.intervalTime);
    });
  }

  createPointData = () => {
    const { w, h } = this.props;
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, w, h);
    canvas.width = this.props.w;
    canvas.height = h;
    const img = new Image();
    img.onload = () => {
      ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, w, h);
      const data = ctx.getImageData(0, 0, w, h).data;
      this.setDataToDom(data, w, h);
      this.dom.removeChild(canvas);
    };
    img.crossOrigin = 'anonymous';
    img.src = this.props.image;
  };

  gatherData = () => {
    const children = this.state.children.map(item =>
      React.cloneElement(item, {
        animation: {
          x: 0,
          y: 0,
          opacity: 1,
          scale: 1,
          delay: Math.random() * 500,
          duration: 800,
          ease: 'easeInOutQuint',
        },
      }));
    this.setState({ children });
  };

  disperseData = () => {
    const rect = this.dom.getBoundingClientRect();
    const sideRect = this.sideBox.getBoundingClientRect();
    const sideTop = sideRect.top - rect.top;
    const sideLeft = sideRect.left - rect.left;
    const children = this.state.children.map(item =>
      React.cloneElement(item, {
        animation: {
          x: Math.random() * rect.width - sideLeft - item.props.style.left,
          y: Math.random() * rect.height - sideTop - item.props.style.top,
          opacity: Math.random() * 0.4 + 0.1,
          scale: Math.random() * 2.4 + 0.1,
          duration: Math.random() * 500 + 500,
          ease: 'easeInOutQuint',
        },
      }));

    this.setState({
      children,
    });
  };

  updateTweenData = () => {
    this.dom = ReactDOM.findDOMNode(this);
    this.sideBox = ReactDOM.findDOMNode(this.sideBoxComp);
    ((this.gather && this.disperseData) || this.gatherData)();
    this.gather = !this.gather;
  };
  onChangeInput = (e) =>{
    var value = e.target.value;
    var key = e.target.name;
    var t = {};
    t[key] = value;
    this.setState(t);
  };


  enterLoading = () =>{
    var dic = {
      account: this.state.account,
      pwd: this.state.pwd
    };
    this.props.callBack(dic);
  };

  onKeyup(e){
    var inputs = document.getElementsByTagName("input");
    if (e.target.name == "account" && e.keyCode === 13){
      inputs[1].focus();
    } else if (e.target.name == "pwd" && e.keyCode === 13) {
      this.enterLoading();
    }
  }

  render() {
    return (
      <div className={styles.logo_gather_demo_wrapper}
           onMouseEnter={this.onMouseEnter.bind(this)}
           onMouseLeave={this.onMouseLeave.bind(this)}
      >
        <canvas id="canvas" />
        <Row className={styles.login_div}>
          <Col xs={{ span: 20, offset: 4 }}>
            <div className={styles.login_header_div}>
              <div className={styles.login_header_logo_div}>
                <img className={styles.login_header_logo} src={logoImgs} />
                <span className={styles.login_header_text}>{global.projectName}管理系统</span>
              </div>
            </div>
          </Col>
          <Col xs={{ span: 8, offset: 4 }}>
            <TweenOne
              animation={this.state.boxAnim}
              className={styles.right_side}
              onMouseEnter={this.onMouseEnter.bind(this)}
              onMouseLeave={this.onMouseLeave.bind(this)}
              ref={(c) => {this.sideBoxComp = c;}} >
              {this.state.children}
            </TweenOne>
          </Col>
          <Col xs={{ span: 10, offset: 14 }}>
            <div className={styles.login_input_bg}>
              <div className={styles.login_title}>
                <p className={styles.login_title_p}>登录</p>
                <h4 className={styles.login_title_e}>LOGIN</h4>
              </div>
              <div className={styles.login_input_div}>
                <Input name="account" autoComplete="off" className={styles.login_input} onKeyUp={this.onKeyup.bind(this)} onChange={this.onChangeInput.bind(this)} placeholder="用户名" id="account"/>
              </div>
              <div className={styles.login_input_div}>
                <Input name="pwd" autoComplete="off" className={styles.login_input} onKeyUp={this.onKeyup.bind(this)} onChange={this.onChangeInput.bind(this)} placeholder="密码" type="password" id="pwd"/>
              </div>

              <div className={styles.submit_div}>
                <Button className={styles.login_btn} type="primary" onClick={this.enterLoading.bind(this)}>
                  登录
                </Button>
                {
                  //<p className={styles.login_title_xinou}>
                  //  信鸥科技 技术支持
                  //</p>
                }
              </div>
            </div>
          </Col>
          <Col xs={{ span: 20, offset: 4 }} >
            <div className={styles.login_header_footer}>
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}


class Login extends React.Component{

  onChanges(t){
    this.props.dispatch({
      type: "login/submit",
      loading:true
    });
    this.props.dispatch({
      type:  'login/login',
      payload: t
    })
  }

  render(){

    return (
      <div style={{ position: 'relative', height: '100%' }}>
        <LogoGather
          image={imgLogo}
          w={400}
          h={400}
          pixSize={30}
          pointSizeMin={10}
          callBack={this.onChanges.bind(this)}
        />
      </div>
    )
  }
}

export default connect(({login})=>({login}))(Login)
